package filex

import (
	"bufio"
	"gitee.com/zackeus/goutil/fsutil"
	"os"
)

type Writer struct {
	file   *os.File
	engine *bufio.Writer
}

func NewWriter(path string) (*Writer, error) {
	/* 覆盖模式打开 */
	file, err := fsutil.OpenTruncFile(path)
	if err != nil {
		return nil, err
	}
	return &Writer{
		file:   file,
		engine: bufio.NewWriter(file),
	}, nil
}

func (w *Writer) Close() error {
	/* 缓冲流刷盘 */
	_ = w.engine.Flush()
	return w.file.Close()
}

func (w *Writer) Write(p []byte) (nn int, err error) {
	return w.engine.Write(p)
}

func (w *Writer) WriteString(s string) (nn int, err error) {
	nn, err = w.engine.WriteString(s)
	if err != nil {
		return 0, err
	}
	if err = w.engine.Flush(); err != nil {
		return 0, err
	}
	return nn, nil
}

func (w *Writer) Flush() error {
	return w.engine.Flush()
}

func (w *Writer) Stat() (os.FileInfo, error) {
	return w.file.Stat()
}
